package com.wgs.onomastici;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class Onomastici extends AbstractBaseActivity implements OnClickListener {

	private static final int DIALOG_TROVATO = 3;
	private TextView oggi;
	private TextView santi_odierni;
	private Button cerca_data;
	private Button cerca_nome;
	
	private List<Contatto> contatti;

	@SuppressLint("SimpleDateFormat")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_onomastici);

		
		Resources res = getResources();
		setInfoMessage(res.getString(R.string.info_msg_onomastici));
		/************* Ricerca santi in base alla data odierna *************/
		AssetManager manager = getAssets();
		XmlParser parser;
		try {
			parser = XmlParser.getInstance(manager);
			
			
			/************* Determino la data odierna *************/
			Finder finder = new Finder(parser.getDocument());
			
			Calendar cal=Calendar.getInstance();	
			SimpleDateFormat formatter =  new SimpleDateFormat("dd MMMM yyyy");
			String dateNow = formatter.format(cal.getTime());	
			int month = cal.get(Calendar.MONTH)+1;
	        int day = cal.get(Calendar.DAY_OF_MONTH);
			
				
			oggi = (TextView) findViewById(R.id.data_odierna);
			oggi.setGravity(Gravity.CENTER);
			oggi.setTextSize(20);
			oggi.setTypeface(null, 1);
			oggi.setText(dateNow);
			
			List<String> santiOggi=finder.findByDate(String.valueOf(day),String.valueOf(month));
			Collections.sort(santiOggi);
			santi_odierni = (TextView) findViewById(R.id.santi_del_giorno);
			santi_odierni.setGravity(Gravity.CENTER_VERTICAL);
			santi_odierni.setTextSize(20);
			santi_odierni.setTypeface(null, 1);
			santi_odierni.setText(finder.formatSanti(santiOggi));

			/* Ricerca dei contatti fanno match con i santi di oggi */
			contatti=getContactMatch(santiOggi);
			
			
			if (!contatti.isEmpty()){
				Collections.sort(contatti);
				showDialog(DIALOG_TROVATO);
			
			}
			
			/************* Attivazione listener dei pulsanti *************/
			cerca_data = (Button) findViewById(R.id.cerca_per_data);
			cerca_data.setOnClickListener(this);
			cerca_nome = (Button) findViewById(R.id.cerca_per_nome);
			cerca_nome.setOnClickListener(this);
			
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
		
		
		
	
		
	}
	

	@Override
	public void onClick(View v) {

		/************* Apro l'activity in base a quale pulsante viene premuto *************/
		switch (v.getId()) {
		case R.id.cerca_per_data:
			Intent intent_data = new Intent(getApplicationContext(),
					CercaPerData.class);
			startActivity(intent_data);
			break;
		case R.id.cerca_per_nome:
			Intent intent_nome = new Intent(getApplicationContext(),
					CercaPerNome.class);
			startActivity(intent_nome);
			break;
		}
	}
	

	

	

	protected Dialog onCreateDialog(int id, Bundle bundle) {
		Dialog dialog;
		switch (id) {
		case DIALOG_TROVATO:
			dialog = createAlertDialogTrovato();
			break;
		default:
			dialog = null;
			break;
		}
		return dialog;
	}

	private Dialog createAlertDialogTrovato() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Attenzione!");
		builder.setMessage("Hai dei contatti che potrebbero festeggiare oggi l'onomastico");
		builder.setCancelable(true);
		builder.setPositiveButton("Torna all'applicazione",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dismissDialog(DIALOG_TROVATO);
					}
				});
		builder.setNeutralButton("Mostra",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int item) {
						
						ArrayList<String> contact=new ArrayList<String>();
						
						for(int i=0;i<contatti.size();i++){
							
							Contatto c=contatti.get(i);
							
							
							String numeri="";
							for(int k=0;k<c.getPhoneNumbers().size();k++){
								numeri+=c.getPhoneNumbers().get(k);
								if (k<c.getPhoneNumbers().size()-1) numeri+=";";	
							}
							
							
							contact.add(c.getName()+"\n"+numeri);
						}
						
						Bundle bundle=new Bundle();
						bundle.putStringArrayList("contact", contact);
						Intent messaggio = new Intent(getApplicationContext(),
								ListaContatti.class);
						messaggio.putExtras(bundle);
						startActivity(messaggio);
					}
				});
		AlertDialog alert = builder.create();
		return alert;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_onomastici, menu);
		return true;
	}

	private List<Contatto> getContactMatch(List<String> santiOggi) {
		ContentResolver content = getContentResolver();
		
		Uri phoneUri = Phone.CONTENT_URI;
		List<Contatto> contatti=new ArrayList<Contatto>();
		
		for(String santo:santiOggi){
			
			String[] phoneProjection = {Phone.CONTACT_ID, Phone.NUMBER, Phone.DISPLAY_NAME };
			String selection=" "+Contacts.DISPLAY_NAME+" LIKE ?";
			String[] selectionArgs=new String[1];
			selectionArgs[0]="%"+santo+"%";
			String orders = Phone.CONTACT_ID + " ASC";
			
			Cursor phoneCursor = content.query(phoneUri, phoneProjection, selection,selectionArgs, orders);
			
			Contatto lastContact=null;
			while (phoneCursor.moveToNext()) {
				
				Integer contactId=phoneCursor.getInt(0);
				
				if (lastContact==null){
					 
					 lastContact=new Contatto();
					 lastContact.setId(contactId);
					 lastContact.setName(phoneCursor.getString(2));
					 contatti.add(lastContact);
					
				}else if(!lastContact.getId().equals(contactId)){
					Contatto findContact=null;
					for(int i=0;i<contatti.size();i++){
						if (contatti.get(i).getId().equals(contactId)){
							findContact=contatti.get(i);
							break;
						}
						
					}
					if (findContact==null) {
						 findContact=new Contatto();
						 findContact.setId(contactId);
						 findContact.setName(phoneCursor.getString(2));
						 contatti.add(findContact);
						 
					}
					lastContact=findContact;
				}
				
				if (lastContact.getPhoneNumbers()==null) lastContact.setPhoneNumbers(new ArrayList<String>());
				
				lastContact.getPhoneNumbers().add(phoneCursor.getString(1).replaceAll("-", ""));
				
			}
			
		}
		
	
		return contatti;
	}

}
